package org.fuys.coder.common.util;

import org.fuys.coder.common.entity.Pair;
import org.fuys.coder.common.exception.BusinessException;

/**
 * @projectName: fuys-low-coder
 * @package: org.fuys.coder.common.util
 * @className: BitOperationUtil
 * @author: WangJing
 * @description: 位操作工具类
 * @date: 2024/6/30 15:56
 * @version: 1.0
 */
public class BitOperationUtil {

    private static final int MAX_BIT_INDEX=31;
    private static final int MIN_BIT_INDEX=0;

    //在指定比特位设置值 value表示设置0或1
    public static long setLongBit(long longBit,int bitIndex,boolean value){
        if(bitIndex>MAX_BIT_INDEX || bitIndex<MIN_BIT_INDEX){
            throw new BusinessException("无法处理的位操作 设定索引值超出范围"+bitIndex);
        }
        long bitMask=1L<<bitIndex;
        if(value){
            longBit|=bitMask;
        }else{
            longBit&=~bitMask;
        }
        return longBit;
    }

    public static boolean getLongBit(long longBit,int bitIndex){
        if(bitIndex>MAX_BIT_INDEX || bitIndex<MIN_BIT_INDEX){
            throw new BusinessException("无法处理的位操作 设定索引值超出范围"+bitIndex);
        }
        final long bitMask=1L<<bitIndex;
        return (bitMask&longBit)!=0;
    }

    //从0到30 分别表示这些天是否进行了签到
    public static Pair<Integer,byte[]> getLongBitInfo(long value){
        int count=0;
        byte[] bytes=new byte[MAX_BIT_INDEX];
        for(int i=0;i<MAX_BIT_INDEX;i++){
            int bitValue=(int)((value>>(i))&1);
            bytes[i]=(byte) bitValue;
            if(bitValue==1)count++;
        }
        return new Pair<>(count,bytes);
    }

}
